<template>
    <div class="chat-area">
        <div class="handler-box">
            <div class="title">{{ chat.currentConversation.name }}</div>
            <div class="left-icon" @click="handleBack(chat.currentConversation.uniqueMark)">
                <svg-icon icon-class="back" size="0.5rem" color="#323b8c"></svg-icon>
            </div>
            <div class="right-icon" @click="">
                <svg-icon icon-class="more" size="0.4rem"></svg-icon>
            </div>
        </div>
        <div v-show="!isLoadMore" class="content-box">
            <div class="top-operations" :key="Date.now()">
                <span v-if="chat.currentConversation.pageNum > 1">
                    <svg-icon icon-class="more-msg" size="0.3rem"></svg-icon>
                    <span class="operation-text" @click="loadMore">点击加载更多...</span>
                </span>
                <span v-else-if="chat.currentConversation.pageNum === 1" style="text-align: center">没有更多了~</span>
                <span v-else-if="chat.currentConversation.pageNum === 0"
                      style="text-align: center">恭喜两位约友在此结盟!</span>
            </div>
            <div class="msg-list" ref="msgList"
                 v-for="item in chat.currentConversation.singleMsgList">
                <div class="msg left" v-if="item.fromUid !== user.id">
                    <img v-if="chat.currentConversation.img" class="avatar-box" :src="chat.currentConversation.img"
                         alt="author"/>
                    <img v-else class="avatar-box" src="@/assets/images/user/default-author.png"
                         alt="author"/>
                    <div class="msg-content">
                        <HtmlContent v-model:text="item.content"></HtmlContent>
                    </div>
                </div>
                <div class="msg right" v-else>
                    <img v-if="user.avatar" class="avatar-box" :src="user.avatar"
                         alt="author"/>
                    <img v-else class="avatar-box" src="@/assets/images/user/default-author.png"
                         alt="author"/>
                    <div class="msg-content">
                        <HtmlContent v-model:text="item.content"></HtmlContent>
                    </div>
                </div>
            </div>
        </div>
        <div class="bottom">
            <div class="button-box">
                <div class="voice" @click="">
                    <svg-icon icon-class="voice" size="0.5rem"></svg-icon>
                </div>
                <div class="input-text">
                    <!--<textarea placeholder="开约吧..." v-model="msg"></textarea>-->
                    <Editor class="textarea" ref="editorRef" v-model:text="msg" placeholder="开约吧..."
                            @mouseover="handleConnect()"></Editor>
                    <button @click="handleSendMsg()">Go</button>
                </div>
                <div class="expression">
                    <svg-icon icon-class="expression" size="0.5rem" @click="isEmoji = !isEmoji"></svg-icon>
                </div>
                <div class="more">
                    <svg-icon icon-class="more-sign" size="0.5rem"></svg-icon>
                </div>
            </div>
        </div>
        <Emoji class="emoji-box" :class="{sub: isEmoji}" @addEmoji="handleAddEmoji"></Emoji>
    </div>
</template>

<script setup lang="ts">
import useStore from "@/store"
import {DataContent} from "@/model/chat";
import {useWebSocket} from "@/utils/websocket";
import {getRecentMsg, readMsg} from "@/api/msg";
import {MsgQuery} from "@/api/msg/types";

const {user, chat} = useStore();

const editorRef = ref();
const msg = ref('');
const webSocket = ref();
const msgList = ref(null);
const data = reactive({
    scrollBottom: false,
    isLoadMore: false,
    content: "",
    // 是否绑定消息处理函数
    isConnectMsg: false,
    isEmoji: false,
});

const {scrollBottom, isLoadMore, content, isConnectMsg, isEmoji} = toRefs(data);

/**
 * 最后一条消息滚动到可视区域
 */
const handler = () => {
    if (scrollBottom.value) {
        setTimeout(() => {
            const lastItem = document.querySelector('.msg-list:last-child');
            lastItem && lastItem.scrollIntoView();
        }, 0);
    }
};

/**
 * 加载更多消息
 */
const loadMore = () => {
    isLoadMore.value = true;
    getRecentMsg({
        roomId: user.id + '_' + chat.currentConversation.uniqueMark,
        pageNum: --chat.currentConversation.pageNum,
        pageSize: 10,
    } as MsgQuery).then(({data}) => {
        if (data.code === 200) {
            chat.currentConversation.singleMsgList?.unshift(...data.rows)
        }
    });
    isLoadMore.value = false;
}

/**
 * 设置消息类型
 */
const setMsgType = (msg: string): number => {
    return msg.includes('<img') ? 2 : 1;
}

/**
 * 发送消息
 */
const handleSendMsg = () => {
    if (!msg.value.trim().length) {
        return;
    } else {
        webSocket.value.send(JSON.stringify({
            action: 2,
            chatMsg: {
                roomId: user.id + '_' + chat.currentConversation.uniqueMark,
                fromUid: user.id,
                toUid: chat.currentConversation.uniqueMark,
                msgType: setMsgType(msg.value.trim()),
                content: msg.value.trim(),
            },
        } as DataContent));
        msg.value = '';
        editorRef.value.clear();
    }
}

/**
 * 输入表情
 */
const handleAddEmoji = (key: string, value: string) => {
    editorRef.value.addText("<img src= '" + value +
        "' width='20' height='20' alt=" + key +
        " style='margin: 0 1px; vertical-align: text-bottom'/>");
}

/**
 * 退出
 */
const handleBack = (friendId: number) => {
    // 设置所有发给我的消息已读
    readMsg(friendId + '_' + user.id);
    chat.setRecentSingleList();
    chat.chatType = 0;
    editorRef.value.clear();
    isEmoji.value = false;
}

/**
 * socket消息处理函数
 */
function handleMessage(content: any) {
    let str = JSON.parse(content.data);
    console.log("str11=", str.chatMsg);
    chat.currentConversation.singleMsgList?.push(str.chatMsg);
    scrollBottom.value = true;
    handler();
    scrollBottom.value = false;
}

/**
 * 绑定handleMessage消息处理函数
 */
const handleConnect = () => {
    if (!isConnectMsg.value) {
        console.log("开始绑定消息处理函数");
        webSocket.value = useWebSocket(handleMessage);
        isConnectMsg.value = true;
    }
}

onMounted(() => {
    if (user.id) {
        webSocket.value = useWebSocket(handleMessage);
    }
})
</script>

<style scoped lang="scss">

.chat-area {
  position: relative;
  width: 90%;
  height: 12rem;
  margin: 0 auto;
  border-radius: 0.25rem;
  backdrop-filter: blur(0.25rem) saturate(150%);
  border: 0.01rem solid rgba(0, 0, 0, 0.7);
  box-shadow: inset -0.01rem 0 0.1rem #161616,
  inset 0.01rem 0 0.1rem #161616;
  color: var(--main-2-h8);

  /* 单独定义滚动条滑块的样式 */
  ::-webkit-scrollbar {
    width: 0.05rem;
  }

  ::-webkit-scrollbar-thumb {
    background-color: transparent;
  }

  :hover::-webkit-scrollbar-thumb {
    background-color: rgba(190, 190, 190, 0.2);
    border-radius: 0.02rem;
  }

  .handler-box {
    height: 0.8rem;
    border-radius: 0.25rem 0.25rem 0 0;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    box-shadow: 0 0.01rem 0.01rem var(--box-shadow);

    .title {
      position: relative;
      font-size: 0.45rem;
      font-weight: bold;
      display: flex;
      justify-content: center;
      color: var(--main-1);
      line-height: 0.8rem;
    }

    .left-icon {
      position: absolute;
      left: 0.2rem;
      top: 0.15rem;
      width: 0.5rem;
      height: 0.5rem;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      box-shadow: 0.02rem 0.02rem 0.06rem 0.03rem #0f122a,
      -0.02rem -0.02rem 0.06rem 0.03rem #684faf;
      transition: 0.5s;

      &:hover {
        box-shadow: none;
        border: 0.02rem solid var(--main-2);
      }
    }

    .right-icon {
      position: absolute;
      right: 0.2rem;
      top: 0.2rem;

      &:hover {
        -webkit-animation: author-shake 1s;
        animation: 1000ms ease 0ms 1 normal none running author-shake;
      }
    }
  }

  .content-box {
    width: 100%;
    height: 10rem;
    margin: 0.8rem auto 0;
    padding: 0.2rem 0.15rem;
    overflow-y: auto;
    overflow-x: hidden;
    scroll-behavior: smooth;

    .top-operations {
      text-align: center;
    }

    .msg-list {
      width: 100%;
      display: inline-block;

      .msg {
        margin-top: 0.15rem;
        font-family: 'Lato', sans-serif;
      }

      .msg-content {
        padding: 0.1rem 0.15rem 0;
        box-shadow: 0 0 0.06rem 0.03rem var(--box-shadow);
        display: inline-block;
        max-width: calc(100% - 1.6rem);
        border-radius: 0.1rem;
        white-space: pre-wrap;
      }

      .avatar-box {
        width: 0.6rem;
        height: 0.6rem;
        border-radius: 0.1rem;
        box-shadow: 0 0 0.06rem 0.03rem var(--box-shadow);
      }

      .left {
        .msg-content {
          float: left;
          position: relative;
          top: 0;
          left: 0.2rem;
          background: var(--main-2);

          &::before {
            content: "";
            background: var(--main-2);
            position: absolute;
            width: 0.15rem;
            height: 0.15rem;
            left: 0;
            top: 0;
            box-shadow: -0.02rem 0.02rem 0.01rem 0.01rem var(--box-shadow);
            transform: translate(-50%, 0.15rem) rotate(45deg);
          }
        }

        .avatar-box {
          float: left;
        }
      }

      .right {
        .msg-content {
          float: right;
          position: relative;
          top: 0;
          right: 0.2rem;
          background: var(--main-1);

          &::before {
            content: "";
            background: var(--main-1);
            position: absolute;
            width: 0.15rem;
            height: 0.15rem;
            right: 0;
            top: 0;
            box-shadow: 0.02rem -0.02rem 0.01rem 0.01rem var(--box-shadow);
            transform: translate(50%, 0.15rem) rotate(45deg);
          }
        }

        .avatar-box {
          float: right;
        }

        ::-webkit-scrollbar {
          height: 0;
        }
      }
    }

    .msg-list:last-child {
      margin-bottom: 2rem;
    }
  }

  .bottom {
    height: 1.35rem;
    width: 100%;
    border-radius: 0 0 0.25rem 0.25rem;
    position: fixed;
    top: 10.8rem;
    right: 0;
    left: 0;
    bottom: 0.1rem;
    box-shadow: 0 -0.01rem 0.01rem var(--box-shadow);
    color: var(--main-1);
    padding: 0.1rem;

    .button-box {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 1rem;
      width: 100%;

      .voice {
        position: absolute;
        left: 0.2rem;

        &:hover {
          -webkit-animation: author-shake 1s;
          animation: 1000ms ease 0ms 1 normal none running author-shake;
        }
      }

      .input-text {
        width: calc(100% - 2.5rem);
        position: absolute;
        left: 0.9rem;
        display: flex;
        align-items: center;
        border-radius: 0.1rem;

        .textarea {
          width: 90%;
          overflow-wrap: break-word;
          word-wrap: break-word;
          height: 0.6rem;
          font-size: 0.25rem;
          line-height: 0.3rem;
          flex-grow: 1;
          color: var(--text-color);
          resize: none;
          padding: 0.1rem;
          border: none;
          border-radius: 0.1rem 0 0 0.1rem;
          box-shadow: inset 0 0 0.05rem 0.02rem var(--box-shadow);

          &:focus {
            outline: none;
            box-shadow: 0 0 0.05rem 0.02rem var(--box-shadow-c);
          }

          &::selection {
            background-color: var(--main-2);
            color: var(--main-1);
          }
        }

        button {
          width: 0.9rem;
          font-weight: bold;
          font-size: 0.4rem;
          height: 0.6rem;
          border-radius: 0 0.1rem 0.1rem 0;
          color: var(--main-1);
          backdrop-filter: blur(0.25rem) saturate(150%);
          border: none;
          box-shadow: 0.03rem 0.03rem 0.04rem 0.02rem #0f122a,
          -0.02rem -0.02rem 0.04rem 0.02rem var(--box-shadow-c);
          transition: 0.5s;
          font-family: "Fredericka the Great", Mulish, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
          letter-spacing: 0.05rem;

          &:hover {
            transform: scale(0.9);
          }

          &:focus {
            box-shadow: none;
            border: 0.02rem solid var(--main-1);
          }
        }
      }

      .expression {
        position: absolute;
        right: 0.9rem;

        &:hover {
          -webkit-animation: author-shake 1s;
          animation: 1000ms ease 0ms 1 normal none running author-shake;
        }
      }

      .more {
        position: absolute;
        right: 0.2rem;

        &:hover {
          -webkit-animation: author-shake 1s;
          animation: 1000ms ease 0ms 1 normal none running author-shake;
        }
      }
    }
  }

  .emoji-box {
    transform: translateX(3rem);
    transition: 0.5s;
  }

  .emoji-box.sub {
    transform: none;
  }
}
</style>